
package com.scalar.chiptrack.sales.jobs;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;


public class MissedOrderNotificationJob extends JobHandler {

    
    private static final String SALES_ORDER_URI = "/approveOrder.do?salesOrderId=";
    private static final String USER_PROFILE_URI = "userProfile.do";
        
    public void execute() throws Exception {

        ArrayList missedLineItemList = null;
        ArrayList userList = new ArrayList();
        
        ArrayList opUserList = null;
        ArrayList salesUserList = null;
        ArrayList finUserList = null;
        ArrayList mkgUserList = null;
        
        try {
            opUserList = UserDAO.loadUsersWithModifyFunctionAccess (Functionality.OP_APPROVAL_RIGHTS);
            int opUserListSize = opUserList.size();
            for (int i=0; i<opUserListSize; i++) {
                userList.add (opUserList.get (i));
            }
            
            salesUserList = UserDAO.loadUsersWithModifyFunctionAccess (Functionality.SALES_APPROVAL_RIGHTS);
            int salesUserListSize = salesUserList.size();
            for (int i=0; i<salesUserListSize; i++) {
                userList.add (salesUserList.get (i));
            }

            finUserList = UserDAO.loadUsersWithModifyFunctionAccess (Functionality.FINANCE_APPROVAL_RIGHTS);
            int finUserListSize = finUserList.size();
            for (int i=0; i<finUserListSize; i++) {
                userList.add (finUserList.get (i));
            }

            mkgUserList = UserDAO.loadUsersWithModifyFunctionAccess (Functionality.MARKETING_APPROVAL_RIGHTS);
            int mkgUserListSize = mkgUserList.size();
            for (int i=0; i<mkgUserListSize; i++) {
                userList.add (mkgUserList.get (i));
            }
            
            if (userList.isEmpty() == true) {
                System.out.println ("There are zero users to mail the missed orders list...");
                return;
            }
            
            System.out.println ("number of users = " + userList.size());
            
            missedLineItemList = SalesDAO.loadAllMissedLineItems();
            if ((missedLineItemList == null) || (missedLineItemList.size() == 0)) {
                return;
            }
            System.out.println ("number of missed orders = " + missedLineItemList.size());
            sendAlert (missedLineItemList, userList);
        }
        catch (Exception e) {
            System.err.println ("Exception while running MissedOrderNotificationJob: " + e);
            e.printStackTrace();
            throw e;
        }
    }
            
    
    private void sendAlert (ArrayList missedLineItemList, ArrayList userList) throws Exception {
            
        Iterator users = userList.iterator();
        User user = null;
        String email = null;
        StringBuffer emails = new StringBuffer();

        while (users.hasNext()) {
            user = (User) users.next();
            email = user.getEmail();

            if (email != null) {
                emails.append (email).append (Mailer.EMAIL_SEPARATOR);
            }
        }

        String bcc = emails.toString();
        if ((bcc == null) || (bcc.trim().length() == 0)) {
            return;
        }
        bcc = bcc.substring(0, (bcc.length()-1));

        String from = ConfigManager.getSysAdminEmail();
        String to = ConfigManager.getSysAdminEmail();
        String subject = "Missed Sales Order Line Items as of " +  StringUtils.formatDateToString (new Date (System.currentTimeMillis()));
        String message = createMessageBody (missedLineItemList);

        Mailer.send (from, to, null /*cc*/, bcc, subject, message, null /*fileAttachments*/, Mailer.CONTENT_TYPE_HTML);

    }

    
    private String createMessageBody (ArrayList missedLineItemList) {    
        
        Iterator missedLineItems = missedLineItemList.iterator();
        LineItem lineItem = null;
        
        StringBuffer messageBody = new StringBuffer();
        int i=0;
        String bgColor = null;
        
        messageBody.append ("<html><head>\n");
        
        messageBody.append ("<style type=\"text/css\">");
        messageBody.append ("#toc a{ font-family: Verdana;font-style : normal ;font-size : 9pt; font-weight :bold;}");
        messageBody.append ("#toc p{font-family: Verdana;font-style : normal ;font-size : 9pt; font-weight :bold;text-align :center;color :#FFFFFF}");
        messageBody.append ("#toc {border-style : solid;border-color :#000000 ;border-width :medium }");
        messageBody.append ("</style></head><body bgcolor='FDF5E6'>");
        
        messageBody.append ("<h2><u>Missed Sales Order Line Items as of " + StringUtils.formatDateToString (new Date (System.currentTimeMillis())) + "</u></h2>");
        messageBody.append ("<p><table border='0' bgcolor='#FFFFFF'><tr>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Sales Order Number</font></td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Line Item No</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Mkt Part No</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Customer Req Qty</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Unit Price</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Amount</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Booking Date</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Requested Date</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Schedule Date</td>");
        messageBody.append ("<td width='10%' align='center' bgcolor='#993333'><font color='#FFFFFF'>Revised Date</td></tr>");
        
        while (missedLineItems.hasNext()) {
            
            if (i%2 == 0) bgColor = "#FFFFFF";
            else bgColor = "#DEE1E2";

            lineItem = (LineItem) missedLineItems.next();            
            
            messageBody.append ("<tr>");
            messageBody.append ("<td bgColor='" + bgColor + "' align='center' width='10%'>");
            messageBody.append ("<a href='http://").append (ConfigManager.getChipTracHost()).append ("/").append (ConfigManager.getChipTracContext()).append (SALES_ORDER_URI).append (lineItem.getSalesOrderId()).append ("'>"); 
            messageBody.append (lineItem.getSalesOrderNo()).append ("</a>");
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getLineItemNo());
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getMarketingPartNo());
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='right'  width='10%' >").append (StringUtils.formatUnits(lineItem.getQuantity()));
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='right'  width='10%' >").append ("$ ").append (StringUtils.formatAmount(lineItem.getUnitPrice(), null));
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='right'  width='10%' >").append ("$ ").append (StringUtils.formatAmount(lineItem.getAmount(), null));
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getBookingDate());
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getRequestDate());
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='center' width='10%'>").append (lineItem.getScheduleDate());
            messageBody.append ("</td><td nowrap bgColor='" + bgColor + "' align='center' width='10%'>");
            
            if (lineItem.getRevisedDate() != null) {
                messageBody.append (lineItem.getRevisedDate());
            }
            else {
                messageBody.append ("&nbsp");
            }
            messageBody.append ("</td></tr>");
            
            i++;
        }
        
        messageBody.append ("</table>");
        
        // Footer - start
        messageBody.append ("<br><br><br><br><table width='60%' border='0'>");        
        messageBody.append ("<tr><td>___________________________________________________________</td></tr>");
        messageBody.append ("<tr><td><font size=2>You are receiving this email because you have the access rights to</font></td></tr>");
        messageBody.append ("<tr><td><font size=2>approve a sales order from ChipTrac System. If you no longer wish you receive this email</font></td></tr>");
        messageBody.append ("<tr><td><font size=2>Please contact your system administrator.</font></td></tr></table>");
        // Footer - end

        messageBody.append ("<br><br><br></body></html>");
        
        return messageBody.toString();
    }

    
    public static void main (String[] args) throws Exception {
        new MissedOrderNotificationJob().execute();
    }
}